package com.ding.manager.controller.user;

import com.common.base.dao.redis.RedisDao;
import com.ding.manager.config.DTConstant;
import com.ding.manager.controller.base.ManagerBaseController;
import com.ding.manager.filter.DTSessionFilter;
import com.ding.manager.service.ApproveService;
import com.ding.manager.util.ConstantMsgUtil;
import com.ding.manager.util.PageData;
import com.ding.manager.util.ResponseEntity;
import com.ding.manager.vo.DTUser;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiSnsGetPersistentCodeRequest;
import com.dingtalk.api.request.OapiSnsGetSnsTokenRequest;
import com.dingtalk.api.request.OapiSnsGetuserinfoRequest;
import com.dingtalk.api.response.OapiSnsGetPersistentCodeResponse;
import com.dingtalk.api.response.OapiSnsGetSnsTokenResponse;
import com.dingtalk.api.response.OapiSnsGetuserinfoResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 钉钉扫码登陆
 * Description: 验证完成存于redis
 * @auther: xumy
 * @date: 2018/11/13 14:41
 */
@RestController
@RequestMapping("/dtUser")
public class DTUserController extends ManagerBaseController {

    @Resource(name = "redisDao")
    private RedisDao redisDao;

    @Resource(name = "approveService")
    private ApproveService approveService;



    @RequestMapping(value = "/userLogin")
    public ResponseEntity userLogin(HttpServletRequest request) throws Exception {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            PageData pd = this.getPageData();
            PageData ppDa = new PageData();
            String tmp_auth_code = pd.getString("code");

            OapiSnsGetPersistentCodeResponse response = getPersisCode(tmp_auth_code);
            if(null!=response&&DTConstant.resCode.equals(response.getErrcode())) {
                String openid = response.getOpenid();
                String persistent_code = response.getPersistentCode();

                OapiSnsGetSnsTokenResponse snsRes = getSnsToken(openid, persistent_code);
                if(null!=snsRes&&DTConstant.resCode.equals(snsRes.getErrcode())) {
                    String sns_token = snsRes.getSnsToken();

                    OapiSnsGetuserinfoResponse userRes = getUserInfo(sns_token);
                    if(null!=snsRes&&DTConstant.resCode.equals(snsRes.getErrcode())) {
                        OapiSnsGetuserinfoResponse.UserInfo userInfo = userRes.getUserInfo();
                        DTUser dtUser = DTSessionFilter.saveTokenCmnUser(request,userInfo);
                        ppDa.put("publicKey", dtUser.getPublicKey());
                        ppDa.put("user", dtUser);
                        responseEntity.setResponseObject(ppDa);
                        responseEntity.setMsg("登陆成功!");
                    }else {
                        logger.info("获取UserInfo失败");
                        responseEntity.setMsg("登陆失败");
                        responseEntity.setStatus(ConstantMsgUtil.getFailStatus());
                    }
                }else {
                    logger.info("获取SnsToken失败");
                    responseEntity.setMsg("登陆失败");
                    responseEntity.setStatus(ConstantMsgUtil.getFailStatus());
                }
            }else {
                logger.info("获取PersisCode失败");
                responseEntity.setMsg("登陆失败");
                responseEntity.setStatus(ConstantMsgUtil.getFailStatus());
            }
        } catch (Exception e) {
            logger.info("登录失败失败~~~", e);
            responseEntity.setMsg("登录失败!");
            responseEntity.setStatus(ConstantMsgUtil.getFailStatus());
        }
        return responseEntity;
    }

    @RequestMapping(value = "/loginOut")
    public ResponseEntity loginOut(HttpServletRequest request) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            DTSessionFilter.removeTokenDTUser(request);
        } catch (Exception e) {
            logger.info("用户退出登录失败~~~", e);
            responseEntity.setMsg("退出登录失败!");
            responseEntity.setStatus(ConstantMsgUtil.getFailStatus());
        }
        return responseEntity;
    }

    public OapiSnsGetPersistentCodeResponse getPersisCode(String tmp_auth_code) throws Exception{
        DingTalkClient client = new DefaultDingTalkClient(DTConstant.GET_PERSISTENT_CODE_URL);
        OapiSnsGetPersistentCodeRequest request = new OapiSnsGetPersistentCodeRequest();
        request.setTmpAuthCode(tmp_auth_code);
        if(StringUtils.isEmpty(DTConstant.SNS_ACCESS_TOKEN)){
            DTConstant.getSnsToken();
        }
        OapiSnsGetPersistentCodeResponse response = client.execute(request,DTConstant.SNS_ACCESS_TOKEN);
        return response;
    }

    public OapiSnsGetSnsTokenResponse getSnsToken(String openid, String persistent_code) throws Exception{
        DingTalkClient client = new DefaultDingTalkClient(DTConstant.GET_SNS_TOKEN_URL);
        OapiSnsGetSnsTokenRequest request = new OapiSnsGetSnsTokenRequest();
        request.setOpenid(openid);
        request.setPersistentCode(persistent_code);
        if(StringUtils.isEmpty(DTConstant.SNS_ACCESS_TOKEN)){
            DTConstant.getSnsToken();
        }
        OapiSnsGetSnsTokenResponse response = client.execute(request,DTConstant.SNS_ACCESS_TOKEN);
        return response;
    }

    public OapiSnsGetuserinfoResponse getUserInfo (String sns_token) throws Exception{
        DingTalkClient client = new DefaultDingTalkClient(DTConstant.GETUSERINFO_URL);
        OapiSnsGetuserinfoRequest request = new OapiSnsGetuserinfoRequest();
        request.setSnsToken(sns_token);
        request.setHttpMethod("GET");
        OapiSnsGetuserinfoResponse response = client.execute(request);
        return response;
    }


    /**
     * 导入立项申请
     * @return
     */
    @RequestMapping(value = "/push",produces="application/json")
    public ResponseEntity push(){

        ResponseEntity responseEntity = new ResponseEntity();
        PageData pd = this.getPageData();
        try {
            approveService.insertDeptAndUser();
        } catch (Exception e) {
            logger.info("新建立项申请失败", e);
            responseEntity.setMsg("新建立项申请失败!");
            responseEntity.setStatus(ConstantMsgUtil.getFailStatus());
        }
        return responseEntity;
    }


}
